package com.honglv.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.honglv.pojo.entity.Sms;
import com.honglv.pojo.result.Result;
import com.honglv.service.SendCodeService;
import com.honglv.utils.RegexUtil;
import com.honglv.utils.SendCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.honglv.constant.MessageConstant.*;

/**
 * @Auther: 生
 * @Date: 2024/04/06/18:51
 * @Description:
 */
@Service
@Slf4j
public class SendCodeServiceImpl implements SendCodeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Result sendCode(String phone,Integer status) {
        //校验手机号
        if(RegexUtil.isPhoneInvalid(phone)){
            //不符合手机号格式  返回错误信息
            return Result.error("手机号格式错误");
        }
        //符合格式，生成验证码
        String code = RandomUtil.randomNumbers(6);
        //检查为申请类型
        String sendMeg;
        if(status == 0){
            sendMeg = LOGIN_CODE_KEY;
        } else if (status == 1) {
            sendMeg = REGISTER_CODE_KEY;
        }else if(status == -1){
            sendMeg = UPDATEPASSWORD_CODE_KEY;
        }else {
            return Result.error("申请错误");
        }
        //保存验证码到redis  key值登录带LOGIN 注册带REGISTER 找回密码带UPDATEPASSWORD
        stringRedisTemplate.opsForValue().set(sendMeg + phone,code,CODE_TTL, TimeUnit.MINUTES);

        //发送验证码
        Sms sms = Sms.builder()
                .phone(phone)
                .code(String.valueOf(code))
                .build();
        SendCodeUtil.sms(sms);

        return Result.success();
    }
}
